package com.mycat.manager.controller.auth;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.mycat.common.entity.InvokeResult;
import com.mycat.dao.dto.auth.RoleAddResourcesDTO;
import com.mycat.dao.dto.auth.RoleAuthTreeDTO;
import com.mycat.dao.dto.common.CommonDTO;
import com.mycat.dao.entity.auth.RefRoleAuth;
import com.mycat.dao.entity.auth.Role;
import com.mycat.service.auth.AuthResourceService;
import com.mycat.service.auth.RoleService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 后台权限模块之角色管理
 *
 * @author Roger
 */
@Controller
@RequestMapping("/role")
public class RoleController {

    private static final Logger logger = LoggerFactory.getLogger(RoleController.class);

    @Autowired
    private RoleService roleService;

    @Autowired
    private AuthResourceService authResourceService;

    /**
     * 进入角色管理页面
     */
    @RequestMapping(method = RequestMethod.GET)
    @RequiresPermissions("role:view")
    public String toList() {
        return "auth/role";
    }

    /**
     * 获取角色数据
     */
    @RequestMapping(value = "/all", method = RequestMethod.GET)
    @RequiresPermissions("role:view")
    @ResponseBody
    public ResponseEntity<InvokeResult<List<Role>>> all() {
        InvokeResult invokeResult = null;
        try {
            List<Role> list = roleService.findRoles();
            if (null != list && list.size() > 0) {
                invokeResult = InvokeResult.success(list);
            } else {
                invokeResult = InvokeResult.pass_no_data();
            }
        } catch (Exception e) {
            invokeResult = InvokeResult.error();
            logger.error(e.getMessage(), e);
        }
        return new ResponseEntity<>(invokeResult, HttpStatus.valueOf(invokeResult.getCode()));
    }

    /**
     * 获取分页数据
     *
     * @param pageNum  页码
     * @param pageSize 页大小
     */
    @RequestMapping(value = "/{pageNum}/{pageSize}", method = RequestMethod.GET)
    @RequiresPermissions("role:view")
    @ResponseBody
    public ResponseEntity<InvokeResult<PageInfo<Role>>> page(@PathVariable int pageNum, @PathVariable int pageSize) {
        InvokeResult invokeResult = null;
        try {
            Page<Role> page = new Page<Role>() {{
                this.setPageNum(pageNum);
                this.setPageSize(pageSize);
            }};
            PageInfo<Role> pageInfo = roleService.findRoles(page);
            if (null != pageInfo && null != pageInfo.getList() && pageInfo.getList().size() > 0) {
                invokeResult = InvokeResult.success(pageInfo);
            } else {
                invokeResult = InvokeResult.pass_no_data();
            }
        } catch (Exception e) {
            invokeResult = InvokeResult.error();
            logger.error(e.getMessage(), e);
        }
        return new ResponseEntity<>(invokeResult, HttpStatus.valueOf(invokeResult.getCode()));
    }

    /**
     * 获取单个对象
     *
     * @param id Id
     */
    @RequiresPermissions("role:view")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<InvokeResult> getRole(@PathVariable Integer id) {
        InvokeResult invokeResult = null;
        try {
            if (null != id) {
                Role role = roleService.findRole(new Role(id));
                invokeResult = InvokeResult.success(role);
            } else {
                invokeResult = InvokeResult.failure("参数错误！");
            }
        } catch (Exception e) {
            invokeResult = InvokeResult.error();
            logger.error(e.getMessage(), e);
        }
        return new ResponseEntity(invokeResult, HttpStatus.valueOf(invokeResult.getCode()));
    }

    /**
     * 删除对象
     *
     * @param commonDTO 删除数据DTO
     */
    @RequiresPermissions("role:delete")
    @RequestMapping(value = "/delete", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResponseEntity<InvokeResult> delete(@RequestBody CommonDTO commonDTO) {
        InvokeResult invokeResult = null;
        try {
            if (null != commonDTO && null != commonDTO.getIds() && commonDTO.getIds().length > 0) {
                roleService.delRole(commonDTO.getIds());
                invokeResult = InvokeResult.success();
            } else {
                invokeResult = InvokeResult.failure("参数错误！");
            }
        } catch (Exception e) {
            invokeResult = InvokeResult.error();
            logger.error(e.getMessage(), e);
        }
        return new ResponseEntity(invokeResult, HttpStatus.valueOf(invokeResult.getCode()));
    }

    /**
     * 新增数据
     *
     * @param role 新增对象
     */
    @RequiresPermissions("role:add")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<InvokeResult> add(Role role) {
        InvokeResult invokeResult = null;
        try {
            if (null != role) {
                roleService.addRole(role);
                invokeResult = InvokeResult.success();
            } else {
                invokeResult = InvokeResult.failure("参数错误！");
            }
        } catch (Exception e) {
            invokeResult = InvokeResult.error();
            logger.error(e.getMessage(), e);
        }
        return new ResponseEntity(invokeResult, HttpStatus.valueOf(invokeResult.getCode()));
    }

    /**
     * 修改数据
     *
     * @param role 修改对象
     */
    @RequiresPermissions("role:edit")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<InvokeResult> edit(Role role) {
        InvokeResult invokeResult = null;
        try {
            if (null != role && null != role.getId()) {
                roleService.updateRole(role);
                invokeResult = InvokeResult.success();
            } else {
                invokeResult = InvokeResult.failure("参数错误！");
            }
        } catch (Exception e) {
            invokeResult = InvokeResult.error();
            logger.error(e.getMessage(), e);
        }
        return new ResponseEntity(invokeResult, HttpStatus.valueOf(invokeResult.getCode()));
    }

    /**
     * 初始化资源树数据
     */
    @RequiresPermissions("role:auth")
    @RequestMapping(value = "/initAuthTree", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<InvokeResult<List<RoleAuthTreeDTO>>> initAuthTree() {
        InvokeResult invokeResult = null;
        try {
            List<RoleAuthTreeDTO> resources = authResourceService.findAuthTree();
            if (null != resources && resources.size() > 0) {
                invokeResult = InvokeResult.success(resources);
            } else {
                invokeResult = InvokeResult.pass_no_data();
            }
        } catch (Exception e) {
            invokeResult = InvokeResult.error();
            logger.error(e.getMessage(), e);
        }
        return new ResponseEntity<>(invokeResult, HttpStatus.valueOf(invokeResult.getCode()));
    }

    /**
     * 获取当前角色已经授权的资源
     */
    @RequiresPermissions("role:auth")
    @RequestMapping(value = "/getRoleAuth/{roleId}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<InvokeResult<List<RefRoleAuth>>> getRoleAuth(@PathVariable Integer roleId) {
        InvokeResult invokeResult = null;
        try {
            List<RefRoleAuth> resources = authResourceService.findRoleAuth(roleId);
            if (null != resources && resources.size() > 0) {
                invokeResult = InvokeResult.success(resources);
            } else {
                invokeResult = InvokeResult.pass_no_data();
            }
        } catch (Exception e) {
            invokeResult = InvokeResult.error();
            logger.error(e.getMessage(), e);
        }
        return new ResponseEntity<>(invokeResult, HttpStatus.valueOf(invokeResult.getCode()));
    }

    /**
     * 角色添加资源
     */
    @RequiresPermissions("role:auth")
    @RequestMapping(value = "/addResource", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<InvokeResult> addResource(@RequestBody RoleAddResourcesDTO roleAddResourcesDTO) {
        InvokeResult invokeResult = null;
        try {
            if (null != roleAddResourcesDTO && null != roleAddResourcesDTO.getRoleId()) {
                roleService.addResource(roleAddResourcesDTO.getRoleId(),roleAddResourcesDTO.getResourceIds());
                invokeResult = InvokeResult.success();
            } else {
                invokeResult = InvokeResult.failure("参数错误！");
            }
        } catch (Exception e) {
            invokeResult = InvokeResult.error();
            logger.error(e.getMessage(), e);
        }
        return new ResponseEntity(invokeResult, HttpStatus.valueOf(invokeResult.getCode()));
    }

}
